package Offer.offer;

import domain.ListNode;

/**
 * 链表中的倒数第K个节点
 * @author leiwenkang
 * @date 2020/4/6
 */
public class Test15链表中的倒数第K个节点 {
    public ListNode findLastK(ListNode head, int K) {
        if (head == null) {
            throw new RuntimeException("输入非法！");
        }
        ListNode p1 = head;
        //p1先走 K - 1步
        for (int i = 1; i <= K - 1; i++) {
            if (p1.next == null) {
                throw new RuntimeException("输入非法！");
            }
            p1 = p1.next;
        }

        ListNode p2 = head;
        //p1和p2一起走，直到p1走到尾节点
        while (p1.next != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1;
    }
}
